package com.masterclient.app.modules.purchase;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.bean.goods.ProductSpecificationData;
import com.eoner.baselibrary.bean.goods.SimpleProductDetailData;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.goods.adapter.GoodsImageAdapter;
import com.masterclient.app.modules.purchase.contract.PurchaseProductDetailContract;
import com.masterclient.app.modules.purchase.contract.PurchaseProductDetailPresenter;
import com.masterclient.app.modules.purchase.widget.PurchaseSkuDialog;
import com.masterclient.app.modules.purchase.widget.SelectGoodsDialog;
import com.gyf.immersionbar.ImmersionBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jzvd.JzvdStd;
import io.reactivex.functions.Consumer;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @auther hjian
 * @date 2020/9/21.
 */
@Route(path = AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
public class PurchaseProductDetailActivity extends BaseActivity<PurchaseProductDetailPresenter> implements PurchaseProductDetailContract.View {

    @BindView(R.id.purchase_product_detail_banner)
    ViewPager purchaseProductDetailBanner;
    @BindView(R.id.purchase_product_detail_video)
    JzvdStd purchaseProductDetailVideo;
    @BindView(R.id.purchase_product_detail_banner_num)
    TextView purchaseProductDetailBannerNum;
    @BindView(R.id.purchase_product_detail_banner_layout)
    FrameLayout purchaseProductDetailBannerLayout;
    @BindView(R.id.purchase_product_detail_price)
    TextView purchaseProductDetailPrice;
    @BindView(R.id.purchase_product_detail_price_unit)
    TextView purchaseProductDetailPriceUnit;
    @BindView(R.id.purchase_product_detail_title)
    TextView purchaseProductDetailTitle;
    @BindView(R.id.purchase_product_detail_store_logo)
    ImageView purchaseProductDetailStoreLogo;
    @BindView(R.id.purchase_product_detail_store_name)
    TextView purchaseProductDetailStoreName;
    @BindView(R.id.purchase_product_detail_notice_img)
    ImageView purchaseProductDetailNoticeImg;
    @BindView(R.id.purchase_product_detail_webView)
    WebView purchaseProductDetailWebView;
    @BindView(R.id.purchase_product_detail_back)
    ImageView purchaseProductDetailBack;
    @BindView(R.id.purchase_product_detail_alpha)
    View purchaseProductDetailAlpha;
    @BindView(R.id.purchase_product_detail_scroll)
    NestedScrollView purchaseProductDetailScroll;
    @BindView(R.id.purchase_product_detail_confirm)
    TextView purchaseProductDetailConfirm;
    @BindView(R.id.purchase_bottom_num)
    TextView purchaseBottomNum;
    @BindView(R.id.view_purchase_bottom)
    View viewPurchaseBottom;

    @Autowired(name = "product_id")
    String productId;
    @Autowired(name = "liveId")
    String liveId;

    private SimpleProductDetailData data;
    private GoodsImageAdapter imageAdapter;
    private int mBannerScrollY;
    private ProgressLoginDialog progressDialog;
    private String productsJson;
    private PurchaseSkuDialog dialog;
    private SelectGoodsDialog goodsDialog;
    private RxBus rxBus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_product_detail);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        rxBus = RxBus.$();

        purchaseProductDetailAlpha.getLayoutParams().height = ImmersionBar.getStatusBarHeight(this) + ScreenUtils.dp2px(44);

        mBannerScrollY = ScreenUtils.getScreenWidth() - ImmersionBar.getStatusBarHeight(this) - ScreenUtils.dp2px(44);
        Utils.setDin(purchaseProductDetailBannerNum, this);
        Utils.setDin(purchaseProductDetailPriceUnit, this);
        Utils.setDin(purchaseProductDetailPrice, this);


        purchaseProductDetailScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                float alpha;
                if (scrollY >= mBannerScrollY) {
                    alpha = 1;
                } else if (scrollY <= 0) {
                    alpha = 0;
                } else {
                    alpha = scrollY * 1.0f / mBannerScrollY;
                }
                purchaseProductDetailBack.setImageResource(alpha < 0.3 ? R.mipmap.goods_detail_back_icon : R.mipmap.goods_detail_back_icon0);
                purchaseProductDetailAlpha.setAlpha(alpha);
            }
        });

        purchaseProductDetailBack.setOnClickListener(v -> finish());

        purchaseProductDetailConfirm.setOnClickListener(v -> {
            if (dialog == null) {
                showProgress();
                mPresenter.getProductSpecification(productId);
            }else {
                dialog.show();
            }
        });
        viewPurchaseBottom.setOnClickListener(v -> ARouter.getInstance().build(AroutePath.PURCHASE_SHOP_CART_ACTIVITY).navigation());

        rxBus.OnEvent(rxBus.register(Config.PURCHASE_SUBMIT_ORDER), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                if (dialog != null) dialog.dismiss();
                if (goodsDialog != null) goodsDialog.dismiss();
            }
        });

        mPresenter.getData(productId);
    }

    @Override
    public void showData(SimpleProductDetailData data) {

        this.data = data;
        purchaseProductDetailTitle.setText(data.getTitle());
        purchaseProductDetailPrice.setText(data.getPrice());
        if (!TextUtils.isEmpty(data.getPurchase_num())){
            purchaseBottomNum.setVisibility(View.VISIBLE);
            purchaseBottomNum.setText(data.getPurchase_num());
        }else {
            purchaseBottomNum.setVisibility(View.GONE);
        }

        Utils.setFloatSize(purchaseProductDetailPrice, data.getPrice(), 0.655f);

        purchaseProductDetailStoreName.setText(data.getSeller().getStore_name());
        ViewTransformUtil.glideImageView(mContext, data.getSeller().getLogo(), purchaseProductDetailStoreLogo, new Transformation[]{new CenterCrop(),
                new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);

        if (data.getSeller() != null && !TextUtils.isEmpty(data.getSeller().getSeller_notice())) {
            purchaseProductDetailNoticeImg.setVisibility(View.VISIBLE);
            ViewTransformUtil.glideImageView(mContext, data.getSeller().getSeller_notice(), purchaseProductDetailNoticeImg, R.mipmap.defaults);
        } else {
            purchaseProductDetailNoticeImg.setVisibility(View.GONE);
        }

        String topHtml = "<head><meta charset=\"utf-8\"><meta name=\"viewport\" " +
                "content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, " +
                "user-scalable=0\"><title></title><style>body{margin:0;padding:0}p{margin:0}" +
                "img{display:inline-block;width:100%;line-height:0;}</style></head><body>" +
                "<base href=\"http://www.shihanbainian.com/\"/></body>";

        String html = topHtml.replace("<body><base href=\"http://www.shihanbainian.com/\"/></body>",
                "<body><base href=\"http://www.shihanbainian.com/\"/>" + data.getDesc_image() + "</body>");
        purchaseProductDetailWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);

        purchaseProductDetailBannerNum.setText(new StringBuffer().append("1/").append(data.getImages().size()).toString());
        imageAdapter = new GoodsImageAdapter(data.getProduct_id(), data.getTitle(), data.getImages(), this, data.getVideo(), new GoodsImageAdapter.OnClickViewListener() {
            @Override
            public void getPosition(int position) {
                Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.LOOK_PICTURE_FRAGMENT)
                        .withStringArrayList("urlList", (ArrayList<String>) data.getImages())
                        .withString("product_id", data.getProduct_id())
                        .withString("product_name", data.getTitle())
                        .withInt("position", position)
                        .navigation();
                FragmentHostActivity.openFragment(mContext, fragment);
            }
        });

        purchaseProductDetailBanner.setAdapter(imageAdapter);

        purchaseProductDetailBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                purchaseProductDetailBannerNum.setText(new StringBuffer(String.valueOf(position + 1)).append("/").append(imageAdapter.getCount()).toString());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void showSpecificationData(ProductSpecificationData specificationData) {
        dismissProgress();
        dialog = new PurchaseSkuDialog(this, specificationData, new PurchaseSkuDialog.SkuClickListener() {
            @Override
            public void onSkuClick(PurchaseSkuDialog dialog, int type, String product_id, String num) {
                if (type == 0) {
                    dialog.dismiss();
                    showProgress();
                    mPresenter.addCart(product_id, num);
                } else if (type == 1) {
                    goodsDialog = new SelectGoodsDialog(getActivity(), custodyType -> {
                        showProgress();
                        productsJson = getProductsStr(product_id,num);
                        mPresenter.confirmOrder(productsJson,"2",custodyType);
                    });
                    goodsDialog.show();
                }
            }
        });
        dialog.show();
    }

    @Override
    public void successAddCart(Map<String, String> map) {
        dismissProgress();
        ToastUtil.showToast("加入采购清单成功");
    }

    @Override
    public void confirmOrderSuccess(ConfirmOrderData data, String isCustody) {
        dismissProgress();
        ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY).withString("buy_type", "2").
                withString("buy_product", productsJson).withString("saleType", "4")
                .withString("live_room_id",liveId == null ? "0" : liveId)
                .withString("is_custody", isCustody)
                .withSerializable("confirm_order_data", data).navigation();
    }

    @Override
    public void showFailure(String msg) {
        dismissProgress();
        ToastUtil.showToast(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (rxBus != null) {
            rxBus.unregister(Config.PURCHASE_SUBMIT_ORDER);
        }
    }



    private String getProductsStr(String product_id, String num) {
        JSONObject productsStr = new JSONObject();
        try {
            productsStr.put(product_id, num);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return productsStr.toString();
    }

    private void showProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressLoginDialog(this);
        }
        progressDialog.show();
        progressDialog.setDesc("");
    }

    private void dismissProgress() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
